package com.example.mq.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

// MSG->message
public class MSGQueue {
    // 身份标识
    private String name;

    // 持久化存储：true持久化，false不必持久化
    private boolean durable = false;

    // true：这个队列只能被一个消费者使用；false：所有消费者都能使用这个队列；
    private boolean exclusive = false;

    // 队列没有消费者使用，自动删除
    private boolean autoDelete = false;

    // 创建队列时的一些额外指定参数选项
    private Map<String, Object> arguments = new HashMap<>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isExclusive() {
        return exclusive;
    }

    public void setExclusive(boolean exclusive) {
        this.exclusive = exclusive;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

//    public Map<String, Object> getArguments() {
//        return arguments;
//    }
//
//    public void setArguments(Map<String, Object> arguments) {
//        this.arguments = arguments;
//    }

    public String getArguments() {
        // Map->String
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
            System.err.println("[Exchange] Map->String 失败: " + e.getMessage());
            return "{}";
        }
    }

    // 从数据库读取数据之后，构造Exchange对象，自动调用
    public void setArguments(String argumentJson) {
        // 把参数中的argumentJson，按照JSON格式解析，转成map对象
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(argumentJson, new TypeReference<HashMap<String, Object>>() {});
        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
            throw new IllegalArgumentException("[Exchange] JSON->Map 失败: " + e.getMessage(), e);
        }
    }

    public Object getArguments(String key) {
        return arguments.get(key);
    }
    public void setArguments(String key, Object value) {
        arguments.put(key, value);
    }
}
